package models

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/cy77cc/hioshop/global"
	"math/rand"
	"time"
)

type Region struct {
	Model
	ParentId uint16 `json:"parent_id" gorm:"type:smallint unsigned;default:0"`
	Name     string `json:"name" gorm:"type:varchar(120);default:''"`
	Type     int8   `json:"type" gorm:"type:tinyint;default:2"`
	AgencyId uint16 `json:"agency_id" gorm:"type:smallint unsigned;default:0"`
	Area     uint16 `json:"area" gorm:"type:smallint unsigned;default:0"`
	AreaCode string `json:"area_code" gorm:"type:varchar(10);default:'0'"`
	FarArea  uint   `json:"far_area" gorm:"type:int unsigned;default:0"`
}

func (r Region) GetFullRegionName(provinceId, cityId, districtId uint16) (regionName string) {
	return
}

func (r Region) GetRegionListById(parentId int) (list []Region, err error) {
	ctx := context.Background()
	get := global.REDIS.Get(ctx, fmt.Sprintf("regin_parentId:%d", parentId))
	if get.Err() != nil {
		err = global.DB.Model(&Region{}).Where("parent_id=?", parentId).Find(&list).Error
		data, _ := json.Marshal(list)
		global.REDIS.Set(ctx, fmt.Sprintf("regin_parentId:%d", parentId), data, time.Hour+time.Duration(rand.Intn(50)))
		return
	}
	res, _ := get.Result()
	err = json.Unmarshal([]byte(res), &list)
	return
}
